package com.imy.luascript.base.view;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.OnLifecycleEvent;

import com.imy.luascript.utils.RxUtils;

import rx.subscriptions.CompositeSubscription;

public abstract class BaseCustomViewLifecycle extends BaseCustomViewGroup implements LifecycleObserver {
    protected AppCompatActivity activity;
    private boolean pause = false;
    protected CompositeSubscription mCompositeSubscription;

    public BaseCustomViewLifecycle(Context context) {
        super(context);
    }

    public BaseCustomViewLifecycle(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public BaseCustomViewLifecycle(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void init(Context context, AttributeSet attributeSet) {
        if (mContext instanceof AppCompatActivity) {
            activity = (AppCompatActivity) mContext;
            activity.getLifecycle().addObserver(this);
        }
        if (isBindRxBus()) {
            mCompositeSubscription = RxUtils.getNewCompositeSubIfUnsubscribed(mCompositeSubscription);
            onRxEventSubscriber();
        }
    }

    protected void onRxEventSubscriber() {

    }

    protected boolean isBindRxBus() {
        return false;
    }


    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    public void onCreate() {
//        Log.i(TAG, "onCreate()");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    public void onStart() {
        //Log.i(TAG, "onStart()");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    public void onResume() {
        //Log.i(TAG, "onResume()");
        pause = false;
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    public void onPause() {
        pause = true;
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    public void onStop() {
        //Log.i(TAG, "onStop()");
    }

    protected boolean isPause() {
        return pause;
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    public void onDestroy() {
        Log.i(TAG, "onDestroy()");
        if (activity != null) {
            activity.getLifecycle().removeObserver(this);
            activity = null;
        }
        if (isBindRxBus()) {
            if (this.mCompositeSubscription != null) {
                this.mCompositeSubscription.unsubscribe();
                mCompositeSubscription = null;
            }
        }
        if (unbinder != null) {
            unbinder.unbind();
        }
    }

}
